package cn.wjh.business.asyncTask;

import cn.wjh.business.config.TLateConfig;
import cn.wjh.business.config.YouDaoConfig;
import cn.wjh.business.domain.Language;
import cn.wjh.business.domain.Translate;
import cn.wjh.business.domain.TranslateHistory;
import cn.wjh.business.domain.vo.TranslateVo;
import cn.wjh.business.domain.vo.YouDaoTranslateResultVo;
import cn.wjh.business.service.ILanguageService;
import cn.wjh.business.service.ITranslateHistoryService;
import cn.wjh.business.service.ITranslateService;
import cn.wjh.common.core.redis.RedisCache;
import cn.wjh.common.utils.DateUtils;
import cn.wjh.common.utils.bean.BeanUtils;
import cn.wjh.common.utils.spring.SpringUtils;
import cn.wjh.common.utils.uuid.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.jetbrains.annotations.NotNull;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class BusinessAsyncFactory {

    /**
     * 获取有道翻译对当前文本的所有语言翻译结果
     */
    public static TimerTask saveAllLanguageYouDaoTranslate(TranslateVo translateVo, String createBy, Long userId) {
        final String stringKey = UUID.fastUUID().toString();//加密字符串
        return new TimerTask() {
            @Override
            public void run() {
                TLateConfig config = SpringUtils.getBean(TLateConfig.class);//业务配置
                ILanguageService languageService = SpringUtils.getBean(ILanguageService.class);//语言服务
                YouDaoConfig youDaoConfig = SpringUtils.getBean(YouDaoConfig.class);// 有道翻译
                RedisCache redisCache = SpringUtils.getBean(RedisCache.class);//缓存
                ITranslateService translateService = SpringUtils.getBean(ITranslateService.class);//翻译服务
                List<Language> languageList = languageService.list();//所有语言的
                // 有道翻译返回的结果
                languageList.forEach(language -> {
                    try {
                        YouDaoTranslateResultVo item = youDaoConfig.sendRequest(translateVo.getQ(), translateVo.getFrom(), language.getLanguageCode());
                        Translate translate = getTranslate(item, translateVo.getProductId(), stringKey, createBy,userId);
                        translateService.save(translate); //保存
                        Collection<String> keys = redisCache.keys("translateListCache::*");
                        //清掉缓存
                        keys.forEach(redisCache::deleteObject);
                        /*同步翻译操作记录*/
//                        synchronizationTranslateOperHistory(language, translate, createBy, userId);
                        TimeUnit.SECONDS.sleep(2);
                    } catch (JsonProcessingException | NoSuchAlgorithmException | InterruptedException e) {
//						throw new RuntimeException();
                        e.printStackTrace();
                        return;
                    }
                });
            }
        };
    }

    /**
     * 保存用户当前翻译的版本
     */
    public static TimerTask saveUserCurrentTranslationVersion(TranslateVo translateVo, String createBy,Long userId) {
        final String stringKey = UUID.fastUUID().toString();//加密字符串
        return new TimerTask() {
            @Override
            public void run() {
                YouDaoConfig youDaoConfig = SpringUtils.getBean(YouDaoConfig.class);// 有道翻译
                RedisCache redisCache = SpringUtils.getBean(RedisCache.class);//缓存
                ITranslateService translateService = SpringUtils.getBean(ITranslateService.class);//翻译服务
                ITranslateHistoryService translateHistoryService = SpringUtils.getBean(ITranslateHistoryService.class);
                Set<String> toList = translateVo.getToList();//所有语言的
                if (null == toList || toList.isEmpty()) return;
                TranslateHistory translateHistory = translateHistoryService.getById(translateVo.getTranslateHistoryId());//翻译历史对象
                String q = translateVo.getQ();
                String from = translateVo.getFrom();
                toList.add(from);
                if (null != translateHistory) {
                    //如果有翻译历史 处理翻译历史结果
                    String result = translateHistory.getResult();
                    Map<String, String> resultMap = (Map<String, String>) JSON.parse(result);//{languageCode,value}
                    resultMap.put(from, q);
                    toList.forEach(to -> {
                        String translateVal = resultMap.get(to);
                        YouDaoTranslateResultVo item = new YouDaoTranslateResultVo(to, Collections.singletonList(translateVal), q);
                        Translate translate = getTranslate(item, translateVo.getProductId(), stringKey, createBy,userId);
                        translateService.save(translate); //保存
                        Collection<String> keys = redisCache.keys("translateListCache::*");
                        //清掉缓存
                        keys.forEach(redisCache::deleteObject);
                    });
                } else {
                    // 没有就调用有道的api
                    toList.forEach(to -> {
                        try {
                            YouDaoTranslateResultVo item = youDaoConfig.sendRequest(q, from, to);
                            Translate translate = getTranslate(item, translateVo.getProductId(), stringKey, createBy,userId);
                            translateService.save(translate); //保存
                            Collection<String> keys = redisCache.keys("translateListCache::*");
                            //清掉缓存
                            keys.forEach(redisCache::deleteObject);
                            TimeUnit.SECONDS.sleep(2);
                        } catch (JsonProcessingException | NoSuchAlgorithmException | InterruptedException e) {
                            e.printStackTrace();
                        }
                    });
                }
            }
        };
    }


    /**
     * 获取有道翻译对当前文本的所有语言翻译结果
     */
    public static TimerTask saveAllLanguageYouDaoTranslate(Long productId, String q, String createBy, Long userId) {
        final String stringKey = UUID.fastUUID().toString();//加密字符串
        return new TimerTask() {
            @Override
            public void run() {
                TLateConfig config = SpringUtils.getBean(TLateConfig.class);//业务配置
                ILanguageService languageService = SpringUtils.getBean(ILanguageService.class);//语言服务
                YouDaoConfig youDaoConfig = SpringUtils.getBean(YouDaoConfig.class);// 有道翻译
                ITranslateService translateService = SpringUtils.getBean(ITranslateService.class);//翻译服务
                List<Language> languageList = languageService.list();//所有语言的
                // 有道翻译返回的结果
                languageList.forEach(language -> {
                    try {
                        YouDaoTranslateResultVo item = youDaoConfig.sendRequest(q, config.getCommonLanguage(), language.getLanguageCode());
                        Translate translate = getTranslate(item, productId, stringKey, createBy,userId);
                        translateService.save(translate); //保存
                        /*同步翻译操作记录*/
//                        synchronizationTranslateOperHistory(language, translate, createBy, userId);
                        TimeUnit.SECONDS.sleep(2);
                    } catch (JsonProcessingException | NoSuchAlgorithmException | InterruptedException e) {
//						throw new RuntimeException();
                        e.printStackTrace();
                        return;
                    }
                });
            }
        };
    }

    /**
     * 组装有道翻译api返回来的结果集
     *
     * @param item      有道的结果集
     * @param productId 产品Id
     * @param stringKey 加密字符串
     * @param createBy  创建人
     * @return 词条对象
     */
    @NotNull
    public static Translate getTranslate(YouDaoTranslateResultVo item, Long productId, String stringKey, String createBy,Long userId) {
        Translate translate = new Translate();
        translate.setProductId(productId); //产品Id
        translate.setStringKey(stringKey);// 加密字符串
        List<String> translation = item.getTranslation();
        String translateVal = translation != null && !translation.isEmpty() ? translation.get(0).toLowerCase() : "";
        translate.setTranslateVal(translateVal); // 翻译的值
        translate.setLanguageCode(item.getLanguageCode()); // 语言编码
        translate.setCreateTime(DateUtils.getNowDate()); // 当前时间
        translate.setCreateBy(createBy); // 创建人
        translate.setUserId(userId); // 创建人
        return translate;
    }

    /**
     * 新增系统默认语言的时候调用这个把其他语言都新增
     */
    public static TimerTask saveAllLanguageTranslate(Long productId, String stringKey, String createBy, Long userId) {
        return new TimerTask() {
            @Override
            public void run() {
                TLateConfig config = SpringUtils.getBean(TLateConfig.class);//业务配置
                ILanguageService languageService = SpringUtils.getBean(ILanguageService.class);//语言服务
                ITranslateService translateService = SpringUtils.getBean(ITranslateService.class);//翻译服务
                RedisCache redisCache = SpringUtils.getBean(RedisCache.class);//缓存
                List<Language> list = languageService.list(new QueryWrapper<Language>().lambda().ne(Language::getLanguageCode, config.getCommonLanguage()));
                list.forEach(item -> {
                    Translate translate = new Translate();
                    translate.setProductId(productId);
                    translate.setStringKey(stringKey);
                    translate.setLanguageCode(item.getLanguageCode());
                    translate.setTranslateVal("");
                    translate.setCreateTime(DateUtils.getNowDate());
                    translate.setCreateBy(createBy);
                    translateService.save(translate);
                    Collection<String> keys = redisCache.keys("translateListCache::*");
                    //清掉缓存
                    keys.forEach(redisCache::deleteObject);
                    /*同步翻译操作记录*/
//                    synchronizationTranslateOperHistory(item, translate, createBy, userId);
                });
            }
        };
    }

    /**
     * 新增语言后，把所有组里的有关这个语言的词条抖添加上
     */
    public static TimerTask saveLanguageAfter(Language language, String createBy, Long userId) {
        return new TimerTask() {
            @Override
            public void run() {
                ITranslateService translateService = SpringUtils.getBean(ITranslateService.class);//翻译服务
                RedisCache redisCache = SpringUtils.getBean(RedisCache.class);//缓存
                List<Translate> list = translateService.list();
                Map<String, List<Translate>> collect = list.stream().collect(Collectors.groupingBy(Translate::getStringKey));
                Set<String> keySet = collect.keySet();
                keySet.forEach(stringKey -> {
                    Translate translate = new Translate();
                    translate.setProductId(1L);
                    translate.setStringKey(stringKey);
                    translate.setTranslateVal("");
                    translate.setLanguageCode(language.getLanguageCode());
                    translate.setCreateTime(DateUtils.getNowDate());
                    translate.setCreateBy(createBy);
                    translateService.save(translate);
                    Collection<String> keys = redisCache.keys("translateListCache::*");
                    //清掉缓存
                    keys.forEach(redisCache::deleteObject);
                    /*同步翻译操作记录*/
//                    synchronizationTranslateOperHistory(language, translate, createBy, userId);
                });
            }
        };
    }

    /**
     * 异步处理用户翻译记录保存
     */
    public static TimerTask saveTranslationHistory(Long userId, TranslateVo translate, Map<String, String> result) {
        return new TimerTask() {
            @Override
            public void run() {
                //翻译历史服务
                ITranslateHistoryService historyService = SpringUtils.getBean(ITranslateHistoryService.class);
                TranslateHistory history = new TranslateHistory();
                history.setCreateTime(DateUtils.getNowDate());
                history.setUserId(userId);
                history.setQ(translate.getQ());
                history.setFromLanguageCode(translate.getFrom());
                history.setToLanguageCode(String.join(",", translate.getToList()));
                history.setResult(JSON.toJSONString(result));
                historyService.insertTranslateHistory(history);
            }
        };
    }



}
